package dm.api;

import java.util.Iterator;
import dm.api.filter.ViewFilter;
import dm.bsi.Backup;
import dm.bsi.Container;
import dm.bsi.Deployment;
import dm.bsi.Image;
import dm.bsi.Log;
import dm.bsi.Node;
import dm.bsi.Service;
import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;
import indi.zjh.dp.verify.CharNotEmptyRule;
import indi.zjh.dp.verify.Check;

public class BackupApi extends Api {

	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = Configuration.getSessionFactory().createSession();
		try
		{
			
			String serviceName = ctx.getRequestParamValue("name").trim();
			
			Check.data(serviceName).desc("服务名称不能为空").rule(new CharNotEmptyRule());
			
			Query<Service> query = new Query<Service>(session);
			Result<Service> result = query.find(Service.class, "`name` = '"+serviceName+"'").result();
			
			if(result.count() == 0)
			{
				throw new Exception("服务 "+serviceName+" 不存在");
			}
			
			Service service = result.iterator().next();
			Deployment deployment = service.getDeployment(session);
			
			if(!service.isBackup())
			{
				service.setBackup(true);
				session.save(service);
				Log.info(session, deployment, "触发服务"+serviceName+"备份操作");
			}
			else 
			{
				Log.info(session, deployment, "服务"+serviceName+"正在进行备份操作");
			}
			session.commit();

			ctx.writeResponse("OK");
		}
		catch(Exception e)
		{
			ctx.writeResponse("FAIL:"+e.getMessage());
			session.rollback();
			e.printStackTrace();
		}
		finally {
			session.close();
		}
	}

}
